package com.cn.ant.modules.wechat.service;

import com.cn.ant.common.persistence.Page;
import com.cn.ant.common.service.BaseService;
import com.cn.ant.common.utils.DateUtils;
import com.cn.ant.common.utils.Identities;
import com.cn.ant.common.utils.StringUtils;
import com.cn.ant.modules.sys.entity.User;
import com.cn.ant.modules.sys.utils.UserUtils;
import com.cn.ant.modules.wechat.dao.AccessTokenYwMapper;
import com.cn.ant.modules.wechat.dao.WeixinAccountMapper;
import com.cn.ant.modules.wechat.entity.WeixinAccount;
import com.cn.ant.modules.wechat.utils.AccessTokenYw;
import com.cn.ant.modules.wechat.utils.WeixinUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 账号管理
 */
@Service("weixinAccountService")
@Transactional(readOnly = true)
public class WeixinAccountServiceImpl extends BaseService {
    @Autowired
    private WeixinAccountMapper weixinAccountMapper;
    @Autowired
    private AccessTokenYwMapper accessTokenYwMapper;

    public WeixinAccount get(String id) {
        return weixinAccountMapper.get(id);
    }

    @Transactional(readOnly = false)
    public void delete(String id) {
        //删除文本消息模板
        //删除欢迎关注语
        //删除关键词
        //删除扩展接口
        //删除自定义菜单
        //删除客户信息
        //删除图文消息模板
        //删除图文消息
        //删除tikit
        //删除消息往来
        //删除微信公众号
        weixinAccountMapper.delete(id);
    }

    @Transactional(readOnly = false)
    public void save(WeixinAccount account) {
        weixinAccountMapper.insert(account);
    }

    @Transactional(readOnly = false)
    public void update(WeixinAccount account) {
        weixinAccountMapper.updateSelective(account);
    }

    @Transactional(readOnly = false)
    public void saveOrUpdate(WeixinAccount account) {
        User user = UserUtils.getUser();
        if (StringUtils.isNotBlank(account.getId())) {
            account.setUserName(user.getLoginName());
            account.setOfficeId(user.getOffice().getId());
            account.setUpdateBy(user.getId());
            account.setUpdateDate(DateUtils.getCurrDate());
            this.update(account);
        } else {
            account.setId(Identities.generateUUID());
            account.setUserName(user.getLoginName());
            account.setOfficeId(user.getOffice().getId());
            account.setCreateBy(user.getId());
            account.setCreateDate(DateUtils.getCurrDate());
            account.setUpdateBy(user.getId());
            account.setUpdateDate(DateUtils.getCurrDate());
            this.save(account);
        }
    }

    /**
     * 查询公众号账号
     *
     * @param param
     * @return
     */
    public Page<WeixinAccount> query(Page<WeixinAccount> page, Map<String, Object> param) {
        List<WeixinAccount> accountList = new ArrayList<WeixinAccount>();
        param.put("startIdx", page.getFirstResult());
        param.put("pageSize", page.getPageSize());
        accountList = weixinAccountMapper.query(param);
        page.setList(accountList);
        page.setCount(weixinAccountMapper.queryCount(param));
        return page;
    }

    public List<WeixinAccount> queryForList(Map<String, Object> param) {
        if (param == null) {
            param = new HashMap<>();
        }
        return weixinAccountMapper.query(param);
    }

    public String getAccessToken() {
        String token = "";
        WeixinAccount account = findLoginWeixinAccount();
        token = account.getAccountAccessToken();
        if (token != null && !"".equals(token)) {
            // 判断有效时间 是否超过2小时
            Date end = new Date();
            Date start = new Date(account.getAddToeknTime()
                    .getTime());
            if ((end.getTime() - start.getTime()) / 1000 / 3600 >= 2) {
                // 失效 重新获取
                String requestUrl = WeixinUtil.access_token_url.replace(
                        "APPID", account.getAccountAppId()).replace(
                        "APPSECRET", account.getAccountAppSecret());
                JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl,
                        "GET", null);
                if (null != jsonObject) {
                    try {
                        token = jsonObject.getString("access_token");
                        // 重置token
                        account.setAccountAccessToken(token);
                        // 重置事件
                        account.setAddToeknTime(new Date());
                        this.saveOrUpdate(account);
                    } catch (Exception e) {
                        token = null;
                        // 获取token失败
                        String wrongMessage = "获取token失败 errcode:{} errmsg:{}"
                                + jsonObject.getInt("errcode")
                                + jsonObject.getString("errmsg");
                    }
                }
            } else {
                return account.getAccountAccessToken();
            }
        } else {
            String requestUrl = WeixinUtil.access_token_url.replace("APPID",
                    account.getAccountAppId()).replace("APPSECRET",
                    account.getAccountAppSecret());
            JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET",
                    null);
            if (null != jsonObject) {
                try {
                    token = jsonObject.getString("access_token");
                    // 重置token
                    account.setAccountAccessToken(token);
                    // 重置事件
                    account.setAddToeknTime(new Date());
                    this.saveOrUpdate(account);
                } catch (Exception e) {
                    token = null;
                    // 获取token失败
                    String wrongMessage = "获取token失败 errcode:{} errmsg:{}"
                            + jsonObject.getInt("errcode")
                            + jsonObject.getString("errmsg");
                }
            }
        }
        return token;
    }


    public String getAccessToken(String accountId) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("weixinAccountId", accountId);
        List<WeixinAccount> accountList = weixinAccountMapper.query(param);
        WeixinAccount weixinAccountEntity = null;
        String token = null;
        if (accountList != null && accountList.size() > 0) {
            weixinAccountEntity = accountList.get(0);
            token = weixinAccountEntity.getAccountAccessToken();
        }
        if (token != null && !"".equals(token)) {
            // 判断有效时间 是否超过2小时
            Date end = new Date();
            Date start = new Date(weixinAccountEntity.getAddToeknTime()
                    .getTime());
            if ((end.getTime() - start.getTime()) / 1000 / 3600 >= 2) {
                // 失效 重新获取
                String requestUrl = WeixinUtil.access_token_url.replace(
                        "APPID", weixinAccountEntity.getAccountAppId()).replace(
                        "APPSECRET", weixinAccountEntity.getAccountAppSecret());
                JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl,
                        "GET", null);
                if (null != jsonObject) {
                    try {
                        token = jsonObject.getString("access_token");
                        // 重置token
                        weixinAccountEntity.setAccountAccessToken(token);
                        // 重置事件
                        weixinAccountEntity.setAddToeknTime(new Date());
                        this.saveOrUpdate(weixinAccountEntity);
                    } catch (Exception e) {
                        token = null;
                        // 获取token失败
                        String wrongMessage = "获取token失败 errcode:{} errmsg:{}"
                                + jsonObject.getInt("errcode")
                                + jsonObject.getString("errmsg");
                    }
                }
            } else {
                return weixinAccountEntity.getAccountAccessToken();
            }
        } else {
            String requestUrl = WeixinUtil.access_token_url.replace("APPID",
                    weixinAccountEntity.getAccountAppId()).replace("APPSECRET",
                    weixinAccountEntity.getAccountAppSecret());
            JSONObject jsonObject = WeixinUtil.httpRequest(requestUrl, "GET",
                    null);
            if (null != jsonObject) {
                try {
                    token = jsonObject.getString("access_token");
                    // 重置token
                    weixinAccountEntity.setAccountAccessToken(token);
                    // 重置事件
                    weixinAccountEntity.setAddToeknTime(new Date());
                    this.saveOrUpdate(weixinAccountEntity);
                } catch (Exception e) {
                    token = null;
                    // 获取token失败
                    String wrongMessage = "获取token失败 errcode:{} errmsg:{}"
                            + jsonObject.getInt("errcode")
                            + jsonObject.getString("errmsg");
                }
            }
        }
        return token;
    }

    public WeixinAccount findLoginWeixinAccount() {
        User user = UserUtils.getUser();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userName", user.getLoginName());
        List<WeixinAccount> acclst = weixinAccountMapper.query(param);
        WeixinAccount weixinAccountEntity = acclst.size() != 0 ? acclst.get(0) : null;
        if (weixinAccountEntity != null) {
            return weixinAccountEntity;
        } else {
            weixinAccountEntity = new WeixinAccount();
            // 返回个临时对象，防止空指针
            weixinAccountEntity.setWeixinAccountId("-1");
            weixinAccountEntity.setId("-1");
            return weixinAccountEntity;
        }
    }

    /**
     * 查询登录用户的公众号的
     * @return
     */
    public List<WeixinAccount> findByLoginUser(){
        User user = UserUtils.getUser();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("officeId", user.getOffice().getId());
        List<WeixinAccount> acclst = weixinAccountMapper.query(param);
        return acclst;
    }


    public List<WeixinAccount> findByUsername(String username) {
        User user = UserUtils.getUser();
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("userName", user.getLoginName());
        List<WeixinAccount> acclst = weixinAccountMapper.query(param);
        return acclst;
    }

    public WeixinAccount findByToUsername(String toUserName) {
        //weixin_accountid
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("weixinAccountId", toUserName);
        List<WeixinAccount> accountList = weixinAccountMapper.query(param);
        if (accountList != null && accountList.size() > 0) {
            return accountList.get(0);
        } else {
            return null;
        }
    }

    public List<WeixinAccount> queryAccountByAccountnumber(String accountnumber) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("accountnumber", accountnumber);
        return weixinAccountMapper.query(param);
    }

    /**
     * 根据公众号ID查询access_token
     * @param accountId
     * @return
     */
    public AccessTokenYw getRealAccessToken(String appid){
        return accessTokenYwMapper.getRealAccessToken(appid);
    }

    @Transactional(readOnly = false)
    public void updateAccessToken(AccessTokenYw accessTocken) {
        accessTokenYwMapper.update(accessTocken);
    }

    @Transactional(readOnly = false)
    public void saveAccessToken(AccessTokenYw accessTokenYw) {
        accessTokenYwMapper.insert(accessTokenYw);
    }
}